 //
//  SIPInterface.m
//  SIP
//
//  Created by wrt on 13-9-29.
//  Copyright (c) 2013年 wrt. All rights reserved.
//  

#import "SIPInterface.h"
#include "wrt_sip_caller.h"
#import "ContactsDateBase.h"
#import "FriendRespondDateBase.h"
#import "PromptChatDateBase.h"
#import "AlarmDataBase.h"
#import "IncomingMessage.h"
#import "PromptChatMessage.h"
#import "FriendRespondMessage.h"
#import "AlarmMessage.h"
#import "TFHpple.h"

#define INCOMINGNOTANSWER 100001
#define INCOMINGANSWER 100002

//c语言的回调函数
int my_receive_state(unsigned long msgid,void* param)
{
    if(msgid == MSGID_REGISTER_STATE) //注册状态时
    {
        int state = *(int*)param;
        NSLog(@"%d",state);
        if (state == 0)
        {
            NSLog(@"注册失败");
            [[SIPInterface shareSIPInterface].delegate registerFailed]; //发出代理请求
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSString *tempStatus = [defaults valueForKey:@"ISLIVEINBACKGROUND"];
            if ([tempStatus isEqualToString:@"yes"])
            {
//                [[SIPInterface shareSIPInterface] closeRegisterUsers];
//                [[SIPInterface shareSIPInterface] startRegisterUsers];
            }
        }
        if (state == 1)
        {
            NSLog(@"注册成功");
            [[SIPInterface shareSIPInterface].delegate registerSuccessful];  //发出代理请求
        }
        if (state == 2)
        {
            NSLog(@"取消注册");
        }
        return 0;
    }
    
    if (msgid == MSGID_OUTGOING_CALL_INIT) //主动呼叫开始
    {
        [SIPInterface shareSIPInterface].callID = *(int *)param;
        [[SIPInterface shareSIPInterface].delegate outgoingCallBegin];
        return 0;
    }
    
    if (msgid == MSGID_OUTGOING_CALL_RINGING) //主动呼叫，远端在响铃，参数callid
    {
        return 0;
    }
    
    if (msgid == MSGID_OUTGOING_CALL_ANSWERED) //如果是被叫，则自己摘机后触发。如果是主动呼叫，则对方摘机触发， 参数是对应的callid
    {
        [[SIPInterface shareSIPInterface].delegate callAnswer];  //发出代理请求
        return 0;
    }
    
    if (msgid == MSGID_CALL_MEDIA_RUNNING)  //开始通话 有对应的参数callid
    {
        return 0;
    }
    
    if (msgid == MSGID_OUTGOING_CALL_PROGRESS) //主动呼叫正在进行中， 参数是对应的callid
    {
        int callid = *(int *)param;
        NSLog(@"%d",callid);
        return 0;
    }
    
    if (msgid == MSGID_INCOMING_CALL)  //收到一路呼叫 参数struct _incoming_call_info
    {
        struct display_name_info      //来电的人的姓名
        {
            char 	nick[WRT_LEN];
            char 	nickName[WRT_LEN];
        };
        
        struct incoming_call_info   //来电的相关信息 （id和姓名信息）
        {
            int call_id;
            struct display_name_info display_info;
        } info;
        memcpy(&info, param, sizeof(info));
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setInteger:INCOMINGNOTANSWER forKey:@"INCOMINGANSWERSTATUS"];
        [defaults synchronize];
        
        const char *name = info.display_info.nickName;
        NSString *nameStr = [NSString stringWithUTF8String:name];
        const char *displayName = info.display_info.nick;
        NSString *disNameStr = [NSString stringWithUTF8String:displayName];
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        interface.incomingNumber = [[NSString alloc] init];
        interface.incomingNumber = nameStr;   //将来电的号码记录下来
        interface.incomingDisplayName = [[NSString alloc] init];
        interface.incomingDisplayName = disNameStr;   //将来电的昵称记录下来
        interface.incomingID = info.call_id;  //将来电的id纪录下来
        
        interface.incomingTime = [[NSString alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        interface.incomingTime = [dateFormatter stringFromDate:[NSDate date]]; //将来电的时间记录下来
        
        //用信息通知的方式传递来电信息
        [[NSNotificationCenter defaultCenter] postNotificationName:@"INCOMINGCALL" object:nil];
        
            
        return 0;
    }
    
    if (msgid == MSGID_OPEN_VIDEO_WINDOW)  //刷新打开视频窗口 有对应的callid
    {
        [[SIPInterface shareSIPInterface].delegate openWindow];
        return 0;
    }
    
    if (msgid == MSGID_CLOSE_VIDEO_WINDOW)  //视频窗口结束时 有对应的callid
    {
        return 0;
    }
    
    if (msgid == MSGID_CALL_END)   //呼叫结束，有对应的callid
    {
        [[SIPInterface shareSIPInterface].delegate callEnding];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        long status = [defaults integerForKey:@"INCOMINGANSWERSTATUS"];
        if (status == INCOMINGANSWER)
        {
            //用信息通知的方式 操作数据库存已接来电
            [[NSNotificationCenter defaultCenter] postNotificationName:@"INCOMINGCALLANSWER" object:nil];
        }
        else if (status == INCOMINGNOTANSWER)
        {
            //用信息通知的方式 操作数据库存未接来电
            [[NSNotificationCenter defaultCenter] postNotificationName:@"INCOMINGCALLNOTANSWER" object:nil];
        }
        [defaults removeObjectForKey:@"INCOMINGANSWERSTATUS"];
        return 0;
    }
    
    if (msgid == MSGID_CALL_STATUS)  //当处于呼叫状态， 返回当前的通话和视频的状态
    {
        const char *a = (char *)param;
        NSString *statusString = [NSString stringWithUTF8String:a];
//        NSLog(@"%@",statusString);
        
        //先判断是否开启了显示开关 若开启则显示
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *isDisplayCallStatus = [[NSString alloc] init];
        isDisplayCallStatus = [defaults objectForKey:@"SAVEISDISPLAYCALLSTATUS"];
        if ([isDisplayCallStatus isEqualToString:@"YES"])
        {
            //发送通话信息
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CALLSTATUSINFO" object:statusString];
        }
        return 0;
    }
    
    if (msgid == MSGID_DISPLAY_STATUS)  //显示状态
    {
        const char *a = (char *)param;
        NSString *statusString = [NSString stringWithUTF8String:a];
        NSLog(@"%@",statusString);
//        if ([statusString isEqualToString:@"Not Found"])
//        {
            //发送代理
            if ([SIPInterface shareSIPInterface].delegate && [[SIPInterface shareSIPInterface].delegate respondsToSelector:@selector(changeStatus:)])
            {
                [[SIPInterface shareSIPInterface].delegate changeStatus:statusString];  //发出代理请求
            }
//        }
        return 0;
    }
    
    if (msgid == MSGID_CALL_INFO_RECEIVED)  //收到对方的wrt_control 信息
    {
        return 0;
    }
    
    if (msgid == MSGID_MESSAGE_RECEIVED)
    {
        struct _wrt_instant_message message;
        memcpy(&message, param, sizeof(message));
        unsigned long incomgingID = message.chatroomptr;
        const char *url = message.external_body_url;
        int onlyUserData = message.userdata;
        int msgstatus = message.msgstatus;
        const char *msgChat = message.msg;
        NSString *tempContent = [NSString stringWithUTF8String:msgChat];
        NSString *tempUrl = [NSString stringWithUTF8String:url];
        NSString *tempIsTextOrImg = [[NSString alloc] init];
        if (tempUrl.length > 0)
        {
            tempIsTextOrImg = @"Image";
        }
        else
        {
            tempIsTextOrImg = @"Text";
        }
        
        NSDate *date = [NSDate date];
        NSString *tempTime = [[NSString alloc] init];
        NSDateFormatter *dateForMatter = [[NSDateFormatter alloc] init];
        [dateForMatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        tempTime = [dateForMatter stringFromDate:date];
        
        NSArray *array = [[NSArray alloc] init];
        array = [[SIPInterface shareSIPInterface] getChatRoomPeerUserName:incomgingID];
        
        NSString *tempIP = [[NSString alloc] init];
        NSString *tempUserName = [[NSString alloc] init];
        for (int i = 0; i < array.count ; i++)
        {
            NSArray *tempArray = [[NSArray alloc] init];
            tempArray = [array[i] componentsSeparatedByString:@":"];
            if (i == 0)
            {
                tempUserName = tempArray[1];
            }
            else if (i == 1)
            {
                tempIP = tempArray[0];
            }
        }
        NSRange range = [tempIP rangeOfString:@">"];//判断字符串是否包含
        if (range.location != NSNotFound)//包含
        {
            tempIP = [tempIP stringByReplacingOccurrencesOfString:@">" withString:@""];
        }
        
        IncomingMessage *incomingMsg = [[IncomingMessage alloc] init];
        incomingMsg.messageContent = tempContent;
        incomingMsg.date = date;
        incomingMsg.url = tempUrl;
        incomingMsg.userdata = onlyUserData;
        incomingMsg.textOrImage = tempIsTextOrImg;
        
        PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
        if (msgstatus == 0)   //新的消息已到达
        {
            if (incomgingID == promptChatDB.windowID)  //如果等于当前窗口，就直接弹出并且存数据库
            {
                [promptChatDB saveChatDBWithUserName:tempUserName andIpPort:tempIP andContent:tempContent andisTextOrImg:tempIsTextOrImg andOutOrCome:@"come" andIsSucceed:1 andIsRead:1 andTime:tempTime];
                
                //发送通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HAVENEWFRIENDCHATMESSAGE" object:incomingMsg];
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *isInbackgroundNow = [defaults objectForKey:@"ISLIVEINBACKGROUND"];
                if (isInbackgroundNow != nil)
                {
                    if ([isInbackgroundNow isEqualToString:@"yes"])
                    {
                        PromptChatMessage *proptChatMsg = [[PromptChatMessage alloc] init];
                        proptChatMsg.content = tempContent;
                        proptChatMsg.ipPort = tempIP;
                        proptChatMsg.time = tempTime;
                        proptChatMsg.isTextOrImg = tempIsTextOrImg;
                        proptChatMsg.url = tempUrl;
                        proptChatMsg.userName = tempUserName;
                        //发送有新的即时消息通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"PROMPTCHATTABBAR" object:proptChatMsg];
                    }
                }
                
            }
            else   //如果不等于的话存数据库，并发出通知
            {
                [promptChatDB saveChatDBWithUserName:tempUserName andIpPort:tempIP andContent:tempContent andisTextOrImg:tempIsTextOrImg andOutOrCome:@"come" andIsSucceed:1 andIsRead:0 andTime:tempTime];
                
                PromptChatMessage *proptChatMsg = [[PromptChatMessage alloc] init];
                proptChatMsg.content = tempContent;
                proptChatMsg.ipPort = tempIP;
                proptChatMsg.time = tempTime;
                proptChatMsg.isTextOrImg = tempIsTextOrImg;
                proptChatMsg.url = tempUrl;
                proptChatMsg.userName = tempUserName;
                
                //发送有新的即时消息通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"PROMPTCHATTABBAR" object:proptChatMsg];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"NEWUNREADCHATMESSAGE" object:nil];
            }
        }
        else if (msgstatus == 1)   //消息正在发送中
        {
            NSLog(@"正在发送");
        }
        else if (msgstatus == 2)    //消息已经到达
        {
            NSLog(@"发送成功");
            [promptChatDB saveChatDBWithUserName:tempUserName andIpPort:tempIP andContent:tempContent andisTextOrImg:tempIsTextOrImg andOutOrCome:@"out" andIsSucceed:1 andIsRead:1 andTime:tempTime];
            //发送有新的即时消息通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"MESSAGERETURNISSUCCESS" object:incomingMsg];
        }
        else if (msgstatus == 3)    //消息未发送成功
        {
            NSLog(@"发送失败");
            [promptChatDB saveChatDBWithUserName:tempUserName andIpPort:tempIP andContent:tempContent andisTextOrImg:tempIsTextOrImg andOutOrCome:@"out" andIsSucceed:0 andIsRead:1 andTime:tempTime];
            //发送有新的即时消息通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"MESSAGERETURNISFALSE" object:incomingMsg];
        }
    }
    
    
    if (msgid == MSGID_ALARM_RECEIVED)   //收到报警信息
    {
        const char *a = (char *)param;
        NSString *alarmXMLurl = [NSString stringWithUTF8String:a];
        NSLog(@"%@",alarmXMLurl);
        
        //获取存储的时间
        //表格
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        //用[NSDate date]可以获取系统当前时间
        NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
        
        
        //查找一个可用的全局队列
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //将要做的操作放入队列
        dispatch_async(queue,^{
            
            NSData *htmlData = [[NSData alloc] init];
            htmlData = [alarmXMLurl dataUsingEncoding:NSUTF8StringEncoding];
            //创建一个HPPLE解析器
            TFHpple *htmlHppple=[TFHpple hppleWithXMLData:htmlData];
            
            
            TFHppleElement *tfPublishuri = [htmlHppple peekAtSearchWithXPathQuery:@"//publishuri"];
            NSLog(@"%@",[tfPublishuri text]);
            TFHppleElement *tfAlarmuri = [htmlHppple peekAtSearchWithXPathQuery:@"//alarmuri"];
            NSLog(@"%@",[tfAlarmuri text]);
            TFHppleElement *tfAlarmtype = [htmlHppple peekAtSearchWithXPathQuery:@"//alarmtype"];
            NSLog(@"%@",[tfAlarmtype text]);
            TFHppleElement *tfStarttime = [htmlHppple peekAtSearchWithXPathQuery:@"//starttime"];
            NSLog(@"%@",[tfStarttime text]);
            TFHppleElement *tfEndtime = [htmlHppple peekAtSearchWithXPathQuery:@"//endtime"];
            NSLog(@"%@",[tfEndtime text]);
            TFHppleElement *tfResult = [htmlHppple peekAtSearchWithXPathQuery:@"//result"];
            NSLog(@"%@",[tfResult text]);
            TFHppleElement *tfRemarks = [htmlHppple peekAtSearchWithXPathQuery:@"//remarks"];
            NSLog(@"%@",[tfRemarks text]);
            TFHppleElement *tfTomanager = [htmlHppple peekAtSearchWithXPathQuery:@"//tomanager"];
            NSLog(@"%@",[tfTomanager text]);
            
            AlarmMessage *alarmMsg = [[AlarmMessage alloc] init];
            alarmMsg.publishUri = [tfPublishuri text];
            alarmMsg.alarmUri = [tfAlarmuri text];
            alarmMsg.alarmType = [[tfAlarmtype text] intValue];
            alarmMsg.startTime = [tfStarttime text];
            alarmMsg.endTime = [tfEndtime text];
            alarmMsg.result = [tfResult text];
            alarmMsg.remark = [tfRemarks text];
            alarmMsg.tomanager = [[tfTomanager text] intValue];
            alarmMsg.alarmStatus = @"未读";
            alarmMsg.receiveTime = currentDateStr;
            
            if (!([[tfAlarmtype text] intValue] == 0))
            {
                AlarmDataBase *alarmDB = [AlarmDataBase shareAlarmDataBase];
                [alarmDB writeIntoDatabaseWithAlarmUri:[tfAlarmuri text] andPublishUri:[tfPublishuri text] andStartTime:[tfStarttime text] andEndTime:[tfEndtime text] andResult:[tfResult text] andRemark:[tfRemarks text] andTomanager:[[tfTomanager text] intValue] andAlarmType:[[tfAlarmtype text] intValue]];
                
                //发送有新的报警信息通知，让其在报警信息的cell上显示new
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ALARMTABBAR" object:alarmMsg];
                //发送有新的报警信息消息通知，刷新tableview
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWALARMMSG" object:alarmMsg];
                
            }
            
        });
        
        
        return 0;
    }
    
    
//    if (msgid == MSGID_FRIEND_STATE_CHANAGE)  //好友状态的变化
//    {
//        struct _wrt_friend_info myfiend;
//        memcpy(&myfiend, param, sizeof(myfiend));
//        const char *userName = myfiend.username;
//        NSString *userNameStr = [NSString stringWithUTF8String:userName];
//        NSLog(@"%@",userNameStr);
//        
//        
//        const char *disPlayName = myfiend.displayname;
//        NSString *disPlayNameStr = [NSString stringWithUTF8String:disPlayName];
//        NSLog(@"%@",disPlayNameStr);
//        
//        const char *ipChar = myfiend.domain;
//        NSString *ipStr = [NSString stringWithUTF8String:ipChar];
//        NSLog(@"%@",ipStr);
//        
//        int status = myfiend.status;
//        NSLog(@"%d",status);
//        
//        //获取时间
//        NSString *dateAndTime;
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        dateAndTime = [dateFormatter stringFromDate:[NSDate date]];
//        
//        FriendRespondMessage *frdRspdMsg = [[FriendRespondMessage alloc] init];
//        frdRspdMsg.userName = userNameStr;
//        frdRspdMsg.disPlayName = disPlayNameStr;
//        frdRspdMsg.ip = ipStr;
//        frdRspdMsg.status = status;
//        frdRspdMsg.time = dateAndTime;
//        
//        if (status == WRT_STATUS_OFFLINE)
//        {
//            BOOL tempIsFriend = NO;
//            int tempCount = 0;
//            tempCount = [[ContactsDateBase shareContactsDataBase] isExistAndIsFriendWith:userNameStr andip:ipStr];
//            if (tempCount > 0)
//            {
//                tempIsFriend = YES;
//            }
//            else
//            {
//                tempIsFriend = NO;
//            }
//            
//            if (tempIsFriend == YES)
//            {
//                //离线
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"离线"];
//                
////                //更新昵称
////                FriendRespondDateBase *frdRspdDB = [FriendRespondDateBase shareFriendRespondDateBase];
////                [frdRspdDB updateDBForDisplayNameWithUserName:userNameStr andIP:ipStr andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            else
//            {
//                
//                
//                //对方请求加为好友
//                [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"添加失败"];
//                
//                //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//                //发送有新的好友请求消息通知，刷新tableview
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//            }
//        }
//        else if (status == WRT_STATUS_ONLINE)
//        {
//            //在线或者是对方给予同意答复
//            BOOL tempIsFriend = NO;
//            int tempCount = 0;
//            tempCount = [[ContactsDateBase shareContactsDataBase] isExistAndIsFriendWith:userNameStr andip:ipStr];
//            if (tempCount > 0)
//            {
//                tempIsFriend = YES;
//            }
//            else
//            {
//                tempIsFriend = NO;
//            }
//            
//            if (tempIsFriend == YES)
//            {
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"在线"];
//                
////                //更新昵称
////                FriendRespondDateBase *frdRspdDB = [FriendRespondDateBase shareFriendRespondDateBase];
////                [frdRspdDB updateDBForDisplayNameWithUserName:userNameStr andIP:ipStr andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            else
//            {
//                
//                
//                //对方请求加为好友
//                [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"同意添加"];
//                
//                //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//                //发送有新的好友请求消息通知，刷新tableview
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//                
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"在线" andDisplayName:disPlayNameStr];
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//        }
//        else if (status == WRT_STATUS_BUSY)
//        {
//            //繁忙
//            BOOL tempIsFriend = NO;
//            int tempCount = 0;
//            tempCount = [[ContactsDateBase shareContactsDataBase] isExistAndIsFriendWith:userNameStr andip:ipStr];
//            if (tempCount > 0)
//            {
//                tempIsFriend = YES;
//            }
//            else
//            {
//                tempIsFriend = NO;
//            }
//            
//            if (tempIsFriend == YES)
//            {
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"忙碌"];
//                
//                
////                //更新昵称
////                FriendRespondDateBase *frdRspdDB = [FriendRespondDateBase shareFriendRespondDateBase];
////                [frdRspdDB updateDBForDisplayNameWithUserName:userNameStr andIP:ipStr andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            else
//            {
//                
//                
//                //对方请求加为好友
//                [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"同意添加"];
//                
//                //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//                //发送有新的好友请求消息通知，刷新tableview
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//                
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"忙碌" andDisplayName:disPlayNameStr];
//                
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            
//        }
//        else if (status == WRT_STATUS_NOTDISTURB)
//        {
//            //免打扰
//            BOOL tempIsFriend = NO;
//            int tempCount = 0;
//            tempCount = [[ContactsDateBase shareContactsDataBase] isExistAndIsFriendWith:userNameStr andip:ipStr];
//            if (tempCount > 0)
//            {
//                tempIsFriend = YES;
//            }
//            else
//            {
//                tempIsFriend = NO;
//            }
//            
//            if (tempIsFriend == YES)
//            {
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"勿扰"];
//                
//                
//                //更新昵称
////                FriendRespondDateBase *frdRspdDB = [FriendRespondDateBase shareFriendRespondDateBase];
////                [frdRspdDB updateDBForDisplayNameWithUserName:userNameStr andIP:ipStr andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            else
//            {
//                
//                
//                //对方请求加为好友
//                [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"同意添加"];
//                
//                
//                
//                //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//                //发送有新的好友请求消息通知，刷新tableview
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//                
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"勿扰" andDisplayName:disPlayNameStr];
//                
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            
//        }
//        else if (status == WRT_STATUS_ONTHEPHONE)
//        {
//            
//            //免打扰
//            
//            //从数据库中更新
//            [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"通话中"];
//            
//            //用信息通知的方式传递状态信息
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            
//            
//            
//        }
//        else if (status == WRT_STATUS_OUTTOLUNCH)
//        {
//            
//            //外出就餐
//            BOOL tempIsFriend = NO;
//            int tempCount = 0;
//            tempCount = [[ContactsDateBase shareContactsDataBase] isExistAndIsFriendWith:userNameStr andip:ipStr];
//            if (tempCount > 0)
//            {
//                tempIsFriend = YES;
//            }
//            else
//            {
//                tempIsFriend = NO;
//            }
//            
//            if (tempIsFriend == YES)
//            {
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"外出"];
//                
////                //更新昵称
////                FriendRespondDateBase *frdRspdDB = [FriendRespondDateBase shareFriendRespondDateBase];
////                [frdRspdDB updateDBForDisplayNameWithUserName:userNameStr andIP:ipStr andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            else
//            {
//                
//                
//                //对方请求加为好友
//                [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"同意添加"];
//                
//                //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//                //发送有新的好友请求消息通知，刷新tableview
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//                
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"外出" andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            
//        }
//        else if (status == WRT_STATUS_REJECT)
//        {
//            
//            //对方拒绝加为好友
//            //从数据库中删除
//            [[ContactsDateBase shareContactsDataBase] deleteContactsBDWithUserName:userNameStr andIpPort:ipStr];
//            //用信息通知的方式传递状态信息
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            //通知底层进行删除
//            SIPInterface *interface = [SIPInterface shareSIPInterface];
//            [interface deleteFriendWithUserName:userNameStr andDisPlayName:disPlayNameStr andIp:ipStr];
//            
//            
//            
//            
//            //对方请求加为好友
//            [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"拒绝"];
//            
//            //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//            //发送有新的好友请求消息通知，刷新tableview
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//            
//        }
//        else if (status == WRT_STATUS_ADD)
//        {
//            
//            BOOL tempIsFriend = NO;
//            int tempCount = 0;
//            tempCount = [[ContactsDateBase shareContactsDataBase] isExistAndIsFriendWith:userNameStr andip:ipStr];
//            if (tempCount > 0)
//            {
//                tempIsFriend = YES;
//            }
//            else
//            {
//                tempIsFriend = NO;
//            }
//            
//            if (tempIsFriend == YES)
//            {
//                
//                //从数据库中更新
//                [[ContactsDateBase shareContactsDataBase] updateDBWithUserName:userNameStr andIp:ipStr andStatus:@"在线"];
//                
//                //更新昵称
//                FriendRespondDateBase *frdRspdDB = [FriendRespondDateBase shareFriendRespondDateBase];
//                [frdRspdDB updateDBForDisplayNameWithUserName:userNameStr andIP:ipStr andDisplayName:disPlayNameStr];
//                
//                //用信息通知的方式传递状态信息
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWNOTICE" object:nil];
//            }
//            else
//            {
//                
//                
//                //对方请求加为好友
//                [[FriendRespondDateBase shareFriendRespondDateBase] saveFriendRequstDBWithUserName:userNameStr andDisPlayName:disPlayNameStr andIPport:ipStr andTime:dateAndTime andType:@"请求"];
//                
//                //发送有新的好友请求消息通知，让其在好友请求消息的cell上显示new
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"FRIENDREQUSTFORTABBAR" object:frdRspdMsg];
//                //发送有新的好友请求消息通知，刷新tableview
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWFRIENDREQUEST" object:frdRspdMsg];
//            }
//        }
//    }
    return 0;
}




//Sip对象的单例
static SIPInterface *shareSIPInterface = nil;

@implementation SIPInterface
@synthesize delegate = _delegate, callID = _callID, incomingID = _incomingID;

//Sip对象的初始化
+ (SIPInterface *)shareSIPInterface
{
    @synchronized(self)
    {
        if (shareSIPInterface == nil)
        {
            shareSIPInterface = [[self alloc] init];
        }
    }
    return shareSIPInterface;
}
//开始使用SIP服务
-(void)startSip
{
    wrt_sip_open(NULL, NULL);
    wrt_sip_start();
    wrt_sip_ioctl(SET_LOG_ENABLE_CMD, NULL, 0);
    
}

//设置设备和版本号
- (void)setDeviceName:(NSString *)deviceName andVersionNumber:(NSString *)versionStr
{
    struct _agent_info _agentInfo;
    memset(&_agentInfo, 0, sizeof(_agentInfo));
    const char *deviceNameChar = [deviceName UTF8String];
    strcpy(_agentInfo.agent_name, deviceNameChar);
    const char *versionNumChar = [versionStr UTF8String];
    strcpy(_agentInfo.version, versionNumChar);
    wrt_sip_ioctl(SET_USER_AGENT_CMD, &_agentInfo, sizeof(_agentInfo));
}
//设置对方的窗口
- (void)setWindownId:(UIView *)view
{
//    wrt_sip_set_video_window_id((                                                                                                                                                                                                                                                                                                                                                            unsigned long)nil);
//    NSLog(@"==================%lul",(unsigned long)view);
    wrt_sip_set_video_window_id((                                                                                                                                                                                                                                                                                                                                                            unsigned long)view);
}
//设置自己的视频窗口
- (void)setPreviousWindowId:(UIView *)view
{
    //self
    wrt_sip_set_preview_video_window_id((unsigned long)view);
}
//关闭
- (void)closeSip
{
    wrt_sip_close();
}
//设置用户名和密码
- (void)register:(NSString *)UserName passWord:(NSString *)PassWord
{
    struct _auth_info _auth;
    memset(&_auth, 0, sizeof(_auth));
    const char *username = [UserName UTF8String];
    strcpy(_auth.username, username);
    const char *password = [PassWord UTF8String];
    strcpy(_auth.password, password);
    strcpy(_auth.userid, username);
    wrt_sip_ioctl(SET_AUTH_CMD, &_auth, sizeof(_auth));
}
//设置昵称  参数字符串
- (void)displayName:(NSString *)nick andUserName:(NSString *)username
{
    struct _display_name_info _display;
    const char *tempDisplayNick = [nick UTF8String];
    const char *tempUserName = [username UTF8String];
    memset(&_display, 0, sizeof(_display));
    strcpy(_display.displayname, tempDisplayNick);
    strcpy(_display.username, tempUserName);
    wrt_sip_ioctl(SET_DISPLAY_NAME_CMD, &_display, sizeof(_display));
}
//设置服务器地址
- (void)setServiceAddress:(NSString *)serviceIp andPort:(int)port
{
    struct _proxy_info _proxy;
    memset(&_proxy, 0, sizeof(_proxy));
    const char *IP = [serviceIp UTF8String];
    strcpy(_proxy.ip, IP);
    _proxy.port = port;
    wrt_sip_ioctl(SET_PROXY_SERVER_CMD, &_proxy, sizeof(_proxy));
}
//设置回调函数
- (void)my_callerback
{
    unsigned long callback = (unsigned long)my_receive_state;
    wrt_sip_ioctl(SET_CALLBACK_CMD, &callback, sizeof(callback));
}
//开始注册
- (void)startRegisterUsers
{
    wrt_sip_ioctl(SET_REGISTER_ENABLE_CMD, NULL, 0);
}

//关闭注册
- (void)closeRegisterUsers
{
    wrt_sip_ioctl(SET_REGISTER_DISABLE_CMD, NULL, 0);
}
//直接拨打电话
- (void)directStartCall:(NSString *)phone andIP:(NSString *)serviceIp andPort:(NSString *)port
{
    struct _direct_call_info _direct;
    memset(&_direct, 0, sizeof(_direct));
    const char *IP = [serviceIp UTF8String];
    strcpy(_direct.ip, IP);
    const char *Name = [phone UTF8String];
    strcpy(_direct.username, Name);
    _direct.port = [port intValue];
    wrt_sip_ioctl(DIRECT_CALL_CMD, &_direct, sizeof(_direct));
}
//拨打电话 参数字符串
- (void)start_Call:(NSString *)phone
{
    const char *username = [phone UTF8String];
    NSLog(@"==%s  %@",username,phone);
    wrt_sip_ioctl(CALL_CMD, (void*)username, strlen(username)+1);
}
//接听
- (void)answer_call
{
    int callid = self.incomingID;
    wrt_sip_ioctl(HOLDON_CMD, &callid, sizeof(callid));
    NSLog(@"接听");
}
//挂去电
- (void)hang_call
{
    int callid = self.callID;
    wrt_sip_ioctl(HANGUP_CMD, &callid, sizeof(callid));
    NSLog(@"结束");
}
//挂来电
- (void)hang_incoming
{
    int callid = self.incomingID;
    wrt_sip_ioctl(HANGUP_CMD, &callid, sizeof(callid));
    NSLog(@"结束");
}
//来电开锁
- (void)unlock
{
    int callid =  self.incomingID;
    wrt_sip_ioctl(UNLOCK_CMD, &callid, sizeof(callid));
    NSLog(@"开锁");
}
//去电开锁
- (void)callunlock
{
    int callid =  self.callID;
    wrt_sip_ioctl(UNLOCK_CMD, &callid, sizeof(callid));
    NSLog(@"开锁");
}
//去电铃声设置
- (void)outCallRing:(NSString *)path
{
    const char *musicPath = [path UTF8String];
    wrt_sip_ioctl(SET_RING_BACK_FILE_CMD, (void*)musicPath, strlen(musicPath)+1);
}
//来电铃声设置
- (void)incomingRing:(NSString *)path
{
    const char *musicPath = [path UTF8String];
    wrt_sip_ioctl(SET_LOCAL_RING_FILE_CMD, (void*)musicPath, strlen(musicPath)+1);
}

//视频大小通过与设定名称
- (void)videoSize:(NSString *)name
{
    const char *sizeName = [name UTF8String];
    wrt_sip_ioctl(SET_VIDEO_SIZE_BY_NAME_CMD, (void*)sizeName, strlen(sizeName)+1);
}

//设置视频的上下带宽
- (void)setVideoWidth
{
    int width = 1536;
    wrt_sip_ioctl(SET_VIDEO_DEVICE_CMD, &width, sizeof(width));
}

//是否打开视频
- (void)isOpenVideo:(BOOL)a
{
    if (a == YES)
    {
        wrt_sip_ioctl(SET_VIDEO_ENABLE_CMD, NULL, 0);
    }
    else
    {
        wrt_sip_ioctl(SET_VIDEO_DISABLE_CMD, NULL, 0);
    }
}

//是否打开视频预览
- (void)isOpenSelfVideo:(BOOL)a
{
    if (a == YES)
    {
        wrt_sip_ioctl(SET_VIDEO_PREVIEW_EANBLE_CMD, NULL, 0);
    }
    else
    {
        wrt_sip_ioctl(SET_VIDEO_PREVIEW_DISABLE_CMD, NULL, 0);
    }
}

//前置摄像头
- (void)FonrtDevice:(int)a
{
    int device = a;
    wrt_sip_ioctl(SET_VIDEO_DEVICE_CMD, &device, sizeof(device));
}

//是否打开音频
- (void)isOpenSound:(BOOL)a
{
    if (a == YES)
    {
        wrt_sip_ioctl(SET_AUDIO_ENABLE_CMD, NULL, 0);
    }
    else
    {
        wrt_sip_ioctl(SET_AUDIO_DISABLE_CMD, NULL, 0);
    }
}

//测试回音
- (void)testSound
{
    wrt_sip_ioctl(SET_START_EC_CALIBRATION, NULL, 0);
}

//视频的传输协议
- (void)setVideotransport:(int)transport
{
    if (transport == 1)
    {
        int trans = SIP_TRANSPORTS_UDP;
        wrt_sip_ioctl(SET_SIP_TRANSPORTS_CMD, &trans, sizeof(trans));
    }
    else if (transport == 2)
    {
        int trans = SIP_TRANSPORTS_TCP;
        wrt_sip_ioctl(SET_SIP_TRANSPORTS_CMD, &trans, sizeof(trans));
    }
}

//设置stun服务器
- (void)setStunServer:(NSString *)ip
{
    const char *serverIp = [ip UTF8String];
    wrt_sip_ioctl(SET_STUN_SERVER_CMD, (void*)serverIp, strlen(serverIp)+1);
}

//设置SIP协议使用端口
- (void)setSIPport:(NSString *)port
{
    short sipPort = [port intValue];
    wrt_sip_ioctl(SET_SIP_TRANSPORTS_CMD, &sipPort, sizeof(sipPort));
}
//设置视频RTP接口端口
- (void)setRTPvideoPort:(NSString *)port
{
    short rtpPort = [port intValue];
    wrt_sip_ioctl(SET_VIDEO_RTP_PORT_CMD, &rtpPort, sizeof(rtpPort));
}
//设置音频RTP接口端口
- (void)setRTPsoundPort:(NSString *)port
{
    short rtpPort = [port intValue];
    wrt_sip_ioctl(SET_AUDIO_RTP_PORT_CMD, &rtpPort, sizeof(rtpPort));
}
//设置音视频的上传带宽
- (void)setSoundAndVideoUpWidth:(NSString *)width
{
    int widthInt = [width intValue];
    wrt_sip_ioctl(SET_UPLOAD_BANDWIDTH_CMD, &widthInt, sizeof(widthInt));
}
//设置音视频的下载带宽
- (void)setSoundAndVideoDownWidth:(NSString *)width
{
    int widthInt = [width intValue];
    wrt_sip_ioctl(SET_DOWNLOAD_BANDWIDTH_CMD, &widthInt, sizeof(widthInt));
}
//设置是否打开日志
- (void)isOpenNote:(BOOL)a
{
    if (a == YES)
    {
        wrt_sip_ioctl(SET_LOG_ENABLE_CMD, NULL, 0);
    }
    else
    {
        wrt_sip_ioctl(SET_LOG_DISABLE_CMD, NULL, 0);
    }
}
//设置是否打开留言
- (void)isOpenMsg:(BOOL)a
{
    if (a == YES)
    {
        wrt_sip_ioctl(SET_RECORD_AUDIO_ENABLE_CMD, NULL, 0);
    }
    else
    {
        wrt_sip_ioctl(SET_RECORD_AUDIO_DISABLE_CMD, NULL, 0);
    }
}
//是否打开自动接听
- (void)isOpenAutoAnswer:(BOOL)a
{
    if (a == YES)
    {
        int trans = 1;
        wrt_sip_ioctl(SET_AUTO_ANSWER_CMD, &trans, sizeof(trans));
    }
    else
    {
        int trans = 0;
        wrt_sip_ioctl(SET_AUTO_ANSWER_CMD, &trans, sizeof(trans));
    }
}
//设置自动应答码
- (void)autoAnswerCallNumber:(NSString *)number
{
    int tempNumber = [number intValue];
    wrt_sip_ioctl(SET_180_OR_183_CMD, &tempNumber, sizeof(tempNumber));
}
////添加好友
//- (void)addFriendsWithUserName:(NSString *)userName andDisPlayName:(NSString *)disPlayName andIp:(NSString *)ip
//{
//    struct _wrt_friend_info{
//        char    displayname[WRT_LEN]; //昵称
//        char	username[WRT_LEN]; // 用户名。
//        char 	domain[WRT_LEN]; //域名（IP地址如果端口不是5060则格式为ip:port).
//        int     status; //前面定义的用户状态默认是在线。
//    } _friend;
//    memset(&_friend, 0, sizeof(_friend));
//    if (disPlayName.length > 0)
//    {
//        const char *disName = [disPlayName UTF8String];
//        strcpy(_friend.displayname, disName);
//    }
//    else
//    {
////        _friend.displayname[0] = '\0';
//    }
//    const char *Name = [userName UTF8String];
//    strcpy(_friend.username, Name);
//    const char *friendIP = [ip UTF8String];
//    strcpy(_friend.domain, friendIP);
//    _friend.status = WRT_STATUS_ADD;
//    wrt_sip_ioctl(SET_ADD_FRIEND_CMD, &_friend, sizeof(_friend));
//    
//    
////    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
////    int status = [defaults integerForKey:@"SAVEMYSTATUS"];
////    [self setMyStatusWithInt:status];
//}


//改变自己的状态
- (void)setMyStatusWithInt:(int)stauts
{
    int transStatus = stauts;
    wrt_sip_ioctl(SET_MY_STATE_CMD, &transStatus, sizeof(transStatus));
}

////同意添加好友
//- (void)acceptAddFriendWithUserName:(NSString *)userName andDisPlayName:(NSString *)disPlayName andIp:(NSString *)ip
//{
//    struct _wrt_friend_info{
//        char    displayname[WRT_LEN]; //昵称
//        char	username[WRT_LEN]; // 用户名。
//        char 	domain[WRT_LEN]; //域名（IP地址如果端口不是5060则格式为ip:port).
//        int     status; //前面定义的用户状态默认是在线。
//    } _friend;
//    memset(&_friend, 0, sizeof(_friend));
//    const char *disName = [disPlayName UTF8String];
//    strcpy(_friend.displayname, disName);
//    const char *Name = [userName UTF8String];
//    strcpy(_friend.username, Name);
//    const char *friendIP = [ip UTF8String];
//    strcpy(_friend.domain, friendIP);
//    _friend.status = WRT_STATUS_ONLINE;
//    wrt_sip_ioctl(SET_ADD_FRIEND_CMD, &_friend, sizeof(_friend));
//}
////拒绝添加好友
//- (void)rejectAddFriendWithUserName:(NSString *)userName andDisPlayName:(NSString *)disPlayName andIp:(NSString *)ip
//{
//    struct _wrt_friend_info{
//        char    displayname[WRT_LEN]; //昵称
//        char	username[WRT_LEN]; // 用户名。
//        char 	domain[WRT_LEN]; //域名（IP地址如果端口不是5060则格式为ip:port).
//        int     status; //前面定义的用户状态默认是在线。
//    } _friend;
//    memset(&_friend, 0, sizeof(_friend));
//    const char *disName = [disPlayName UTF8String];
//    strcpy(_friend.displayname, disName);
//    const char *Name = [userName UTF8String];
//    strcpy(_friend.username, Name);
//    const char *friendIP = [ip UTF8String];
//    strcpy(_friend.domain, friendIP);
//    _friend.status = WRT_STATUS_REJECT;
//    wrt_sip_ioctl(SET_DEL_FRIEND_CMD, &_friend, sizeof(_friend));
//}
////删除好友
//- (void)deleteFriendWithUserName:(NSString *)userName andDisPlayName:(NSString *)disPlayName andIp:(NSString *)ip
//{
//    struct _wrt_friend_info{
//        char    displayname[WRT_LEN]; //昵称
//        char	username[WRT_LEN]; // 用户名。
//        char 	domain[WRT_LEN]; //域名（IP地址如果端口不是5060则格式为ip:port).
//        int     status; //前面定义的用户状态默认是在线。
//    } _friend;
//    memset(&_friend, 0, sizeof(_friend));
//    const char *disName = [disPlayName UTF8String];
//    strcpy(_friend.displayname, disName);
//    const char *Name = [userName UTF8String];
//    strcpy(_friend.username, Name);
//    const char *friendIP = [ip UTF8String];
//    strcpy(_friend.domain, friendIP);
//    _friend.status = WRT_STATUS_OFFLINE;
//    wrt_sip_ioctl(SET_DEL_FRIEND_CMD, &_friend, sizeof(_friend));
//}

//主动创建窗口
- (void)creatChatRoomWithUserName:(NSString *)userName
{
    const char *chatUserName = [userName UTF8String];
    unsigned long windowID;
    windowID = wrt_sip_create_chat_room(chatUserName);
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    promptChatDB.windowID = windowID;
}

//销毁聊天窗口
- (void)destoryChatRoom
{
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    unsigned long windowID = promptChatDB.windowID;
    wrt_sip_destroy_chat_room(windowID);
}

//查寻即时消息传递过来的内容
- (NSArray *)getChatRoomPeerUserName:(unsigned long)windowId
{
    unsigned long incomingWindow = windowId;
    char userName[64];
    wrt_sip_get_chat_room_peer_username(incomingWindow, userName);
    NSString *str = [NSString stringWithUTF8String:userName];
    
    NSArray *array = [[NSArray alloc] init];
    array = [str componentsSeparatedByString:@"@"];
    return array;
}

//发送消息
- (void)sendMessageWithUrl:(NSString *)url andOnedata:(int)onedata andTextContent:(NSString *)text
{
    struct _wrt_instant_message{
        unsigned long chatroomptr; //调用wrtsipcreatechatroom 的返回值。
        char    external_body_url[URL_LEN];
        int	userdata;
        int	msgstatus;
        int 	msglen;
        char 	msg[URL_LEN];
    }_message;
    memset(&_message, 0, sizeof(_message));
    
    
//    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//    const char *contentText = [text cStringUsingEncoding:enc];
    
    const char *contentText = [text UTF8String];
    
    
    PromptChatDateBase *promptDb = [PromptChatDateBase sharePromptChatDB];
    unsigned long windowId = promptDb.windowID;
    
    _message.chatroomptr = windowId;
    
    if (url == nil)
    {
        
    }
    else
    {
        const char *chatUrl = [url UTF8String];
        strcpy(_message.external_body_url, chatUrl);
    }
    
    _message.userdata = onedata;
    
    _message.msgstatus = 0;
    
    _message.msglen = (int)strlen(contentText) + 1;
    
    strcpy(_message.msg, contentText);
    
    wrt_sip_ioctl(SEND_MESSAGE_CMD, &_message, sizeof(_message));
}
//根据用户名获取windowID
- (unsigned long)getChatRoomByUserName:(NSString *)name andIPport:(NSString *)ip andPort:(NSString *)port
{
    NSString *tempUserName = [NSString stringWithFormat:@"sip:%@@%@",name,ip];
    const char *userName = [tempUserName UTF8String];
    unsigned long tempWindowId;
    tempWindowId = wrt_sip_get_chatroomptr_by_username(userName);
    return tempWindowId;
}
//进入后台模式
- (void)enterBackground
{
    wrt_sip_refresh_register();
}
//接收包
- (void)iterator
{
    wrt_sip_iterator();
}
//设置报警服务器地址
- (void)setAlarmIPAddressAndPort:(NSString *)address andPort:(NSString *)port
{
    struct _proxy_info{
        int     type;  //0:reg,1:alarm等。
        char 	ip[WRT_LEN];
        int  	port;
        char 	outboundproxy_ip[WRT_LEN];
        int	outboundproxy_port;
    }myserver;
    
    memset(&myserver,0,sizeof(myserver));
    myserver.type = 1;
    const char *chatAddress = [address UTF8String];
    strcpy(myserver.ip,chatAddress);
    int portInt = [port intValue];
    myserver.port = portInt;
    
    wrt_sip_ioctl(SET_PROXY_SERVER_CMD,&myserver,sizeof(myserver));
}
//设置布防或者是撤防
- (void)setAlarmControlArmingOrDisarming:(int)a
{
    if (a == 0) //布防
    {
        int alarmtype = 15;
        wrt_sip_ioctl(SET_PROCESS_ALARM,&alarmtype,sizeof(int));
    }
    else if (a == 1)  //撤防
    {
        int alarmtype = 16;
        wrt_sip_ioctl(SET_PROCESS_ALARM,&alarmtype,sizeof(int));
    }
}
//获取音频编解码接口数量
- (int)getAudioCodeCount
{
    return wrt_sip_get_audio_codecs_count();
}
//获取视频编解码接口数量
- (int)getVideoCodeCount
{
    return wrt_sip_get_video_codecs_count();
}
//获取音频编解码串号
- (unsigned long)getAudioCodeNumber:(int)index
{
    return wrt_sip_get_audio_codecs_payload(index);
}
//获取视频编解码串号
- (unsigned long)getVideocodeNumber:(int)index
{
    return wrt_sip_get_video_codecs_payload(index);
}
//获取音视频解码的名称
- (NSString *)getAudioAndVideoName:(unsigned long)typeNumber
{
    char name[64];
    wrt_sip_get_payload_codecs_mime(typeNumber, name);
    NSString *tempName = [NSString stringWithUTF8String:name];
    return tempName;
}
//调整音视频解码的开关
- (void)setEnabledAudioAndVideo:(unsigned long)typeNumber andOn:(int)onOrOff
{
    wrt_sip_set_enabled_payload(typeNumber, onOrOff);
}
//调整音视频解码的位置
- (void)setAudioAndVideoMove:(unsigned long)typeNumber andDir:(int)dir
{
    wrt_sip_codecs_move(typeNumber, dir);
}
//获取通话状态信息
- (void)getCallStatusDetail
{
    wrt_sip_ioctl(GET_CALL_BASE_STATUS, NULL, 0);
}

@end

//61.144.222.195
//8802  8802
